import os 
import logging 
re_path = 'ai_-basic/AI_Basic_lab/RegrassionAndPredict/8linearregression.py'
logger = logging.getLogger('linearRegrassion')
addHandler = logging.FileHandler(str(re_path) + '.log')
logger.addHandler(addHandler)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
addHandler.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.info('start')

os.chdir('F:/AI_BASIC/ai_-basic/AI_Basic_lab/RegrassionAndPredict')

import pandas as pd
# 二手房数据
house_price_df = pd.read_csv('bj_house_information.csv')

#册除一些不重要的列
to_drop = ['Id', '朝向', '电梯', '装修', '楼层', '小区名称', '地点', '楼龄']
house_price_df_clean = house_price_df.drop(to_drop, axis=1)
# 显示列名
print(house_price_df_clean.columns)
print(house_price_df_clean.head())


# 重新摆放列位置
columns = ['房屋总价', '建筑面积', '区域','户型']
house_price_df_clean = pd.DataFrame(house_price_df_clean, columns = columns)
print(house_price_df_clean.head())

lianjia_total_num = house_price_df_clean['建筑面积'].count()
print('房价数据集总数量为: ' + str(lianjia_total_num))

import matplotlib.pyplot as plt
area = house_price_df_clean['建筑面积']
price = house_price_df_clean['房屋总价']
#支持中文，如果不加此句将无法显示中文
plt.rc('font', family='SimHei', size=13)
plt.scatter(area,price)
plt.xlabel("建筑面积")
plt.ylabel("房屋总价")
plt.show()

# 先根据建筑面积和房屋总价训练模型（一元线性回归）
from sklearn.linear_model import LinearRegression
import numpy as np
linear = LinearRegression()
area = np.array(area).reshape(-1,1) # 这里需要注意新版的sklearn需要将数据转换为矩阵才能进行计算
price = np.array(price).reshape(-1,1)
# 训练模型
model = linear.fit(area,price)
# 打印截距和回归系数
print(model.intercept_, model.coef_)

# 线性回归可视化(数据拟合)
linear_p = model.predict(area)
plt.figure(figsize=(12,6))
plt.scatter(area,price)
plt.plot(area,linear_p,'red')
plt.xlabel("建筑面积")
plt.ylabel("房屋总价")
plt.show()